<?php
namespace app\lib;
use app\BaseController;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
class Jwt extends BaseController
{
    /**
     * 根据json web token设置的规则生成token
     * @return \think\response\Json
     */
    public static function createjwt($userid=null)
    {
        $key = md5(env('TOKEN.key','login')); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $userid,
            "iss" => env('TOKEN.iss','http://www.day.com/index.php/telPwd'),//签发组织
            "aud" => env('TOKEN.aud','cc'), //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        return JWTUtil::encode($token,$key);
    }
    /**
     * 验证token
     * @return \think\response\Json
     */
    public static function verifyjwt($jwt)
    {
//        $jwt=input('token');
        $key = md5(env('TOKEN.key','login'));
        try{
            $jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
            $authInfo = json_decode($jwtAuth,true);
            if (!$authInfo['user_id']){
                return fail('用户不存在');
            }
            return success("ok");
        }catch (ExpiredException $e){
            return fail("token过期");
        }catch (\Exception $e){
            return fail($e->getMessage());
        }
    }
    //从请求信息中获取token令牌
    public static function getRequestToken()
    {
        if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
            return false;
        }
        $header = $_SERVER['HTTP_AUTHORIZATION'];
        $method = 'bearer';
        //去除token中可能存在的bearer标识
        return trim(str_ireplace($method, '', $header));
    }
}